<template>
  <div class="inventory-stat-page">
    <!-- 顶部快速日期 + 筛选 -->
    <el-card class="filter-card" shadow="never">
      <!-- 快速日期 -->
      <div class="quick-tabs">
        <el-radio-group v-model="activeDateTab" size="large" @change="handleDateTabChange">
          <el-radio-button v-for="item in quickDateTabs" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 查询条件表单 -->
      <el-form :model="queryForm" :inline="true" label-width="100px" class="filter-form">
        <!-- 第一行 -->
        <el-form-item label="货品">
          <el-input
            v-model="queryForm.product"
            placeholder="请输入货品名称/编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="货品编号">
          <el-input
            v-model="queryForm.productCode"
            placeholder="请输入货品编号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="盘点单号">
          <el-input
            v-model="queryForm.inventoryCountCode"
            placeholder="请输入盘点单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="盘点类型">
          <el-select
            v-model="queryForm.countTypeId"
            placeholder="请选择"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in countTypeOptions"
              :key="item.countTypeId"
              :label="item.countTypeName"
              :value="item.countTypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-input
            v-model="queryForm.unit"
            placeholder="请输入单位"
            clearable
            style="width: 120px"
          />
        </el-form-item>

        <!-- 第二行 -->
        <el-form-item label="仓库名称">
          <el-select
            v-model="queryForm.warehouseId"
            placeholder="请选择"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经办人">
          <el-input
            v-model="queryForm.handler"
            placeholder="请输入经办人"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="制单人">
          <el-input
            v-model="queryForm.documentCreator"
            placeholder="请输入制单人"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="所在部门">
          <el-input
            v-model="queryForm.organizationName"
            placeholder="请输入所在部门"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="盘点日期">
          <el-date-picker
            v-model="queryForm.countDateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :disabled="activeDateTab !== 'custom'"
            style="width: 260px"
            @change="handleCustomCountDateChange"
          />
        </el-form-item>

        <!-- 第三行 -->
        <el-form-item label="制单时间">
          <el-date-picker
            v-model="queryForm.documentCreationRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 260px"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-space>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stat-row">
      <el-col :span="4">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-value">{{ statistics.countTimes }}</div>
          <div class="stat-label">盘点次数</div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-value success">{{ statistics.gainQuantity }}</div>
          <div class="stat-label">盘盈数量</div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-value danger">{{ statistics.lossQuantity }}</div>
          <div class="stat-label">盘亏数量</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-value success">{{ formatAmount(statistics.gainCostAmount) }}</div>
          <div class="stat-label">盘盈成本金额</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-value danger">{{ formatAmount(statistics.lossCostAmount) }}</div>
          <div class="stat-label">盘亏成本金额</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <el-space>
          <el-button @click="handleExport">导出</el-button>
          <el-button @click="handleRefresh">刷新</el-button>
        </el-space>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productCode" label="货品编号" min-width="120" />
        <el-table-column prop="productName" label="货品名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="countResultText" label="盘点结果" width="100" />
        <el-table-column prop="specificationModel" label="规格型号" min-width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="productTypeName" label="货品类型" min-width="120" />
        <el-table-column prop="bookedQuantity" label="账面数量" width="100" align="right" />
        <el-table-column prop="countQuantity" label="盘点数量" width="100" align="right" />
        <el-table-column prop="gainQuantity" label="盘盈数量" width="100" align="right">
          <template #default="{ row }">
            <span style="color: #67c23a">{{ row.gainQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lossQuantity" label="盘亏数量" width="100" align="right">
          <template #default="{ row }">
            <span style="color: #f56c6c">{{ row.lossQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bookedAmount" label="账面金额" width="120" align="right">
          <template #default="{ row }">
            {{ formatAmount(row.bookedAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="countAmount" label="盘点金额" width="120" align="right">
          <template #default="{ row }">
            {{ formatAmount(row.countAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="gainAmount" label="盘盈金额" width="120" align="right">
          <template #default="{ row }">
            <span style="color: #67c23a">{{ formatAmount(row.gainAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lossAmount" label="盘亏金额" width="120" align="right">
          <template #default="{ row }">
            <span style="color: #f56c6c">{{ formatAmount(row.lossAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="handlerName" label="经办人" width="100" />
        <el-table-column prop="costUnitPrice" label="成本单价" width="120" align="right">
          <template #default="{ row }">
            {{ formatAmount(row.costUnitPrice) }}
          </template>
        </el-table-column>
        <el-table-column prop="costAmount" label="成本金额" width="120" align="right">
          <template #default="{ row }">
            {{ formatAmount(row.costAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="documentCreator" label="制单人" width="100" />
        <el-table-column prop="organizationName" label="所在部门" min-width="120" />
        <el-table-column prop="documentCreation" label="制单时间" width="130">
          <template #default="{ row }">
            {{ formatDate(row.documentCreation) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageindex"
          v-model:page-size="page.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          :total="page.listCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

type QuickDateTab = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth' | 'custom'

interface InventoryStatRow {
  productId: number
  productCode: string
  productName: string
  countResult: number
  countResultText?: string
  specificationModel: string
  unitName: string
  productTypeName: string
  bookedQuantity: number
  countQuantity: number
  gainQuantity: number
  lossQuantity: number
  bookedAmount: number
  countAmount: number
  gainAmount: number
  lossAmount: number
  handlerName: string
  costUnitPrice: number
  costAmount: number
  documentCreator: string
  organizationName: string
  documentCreation?: string
}

interface Statistics {
  countTimes: number
  gainQuantity: number
  lossQuantity: number
  gainCostAmount: number
  lossCostAmount: number
}

const quickDateTabs: Array<{ label: string; value: QuickDateTab }> = [
  { label: '今日', value: 'today' },
  { label: '昨日', value: 'yesterday' },
  { label: '本周', value: 'thisWeek' },
  { label: '上周', value: 'lastWeek' },
  { label: '本月', value: 'thisMonth' },
  { label: '上月', value: 'lastMonth' },
  { label: '自定义时间', value: 'custom' }
]

const activeDateTab = ref<QuickDateTab>('thisMonth')

const queryForm = reactive({
  product: '',
  productCode: '',
  inventoryCountCode: '',
  countTypeId: null as number | null,
  unit: '',
  warehouseId: null as number | null,
  handler: '',
  documentCreator: '',
  organizationName: '',
  countDateRange: [] as string[],
  documentCreationRange: [] as string[]
})

const countTypeOptions = ref<Array<{ countTypeId: number; countTypeName: string }>>([])
const warehouseOptions = ref<Array<{ warehouseId: number; warehouseName: string }>>([])

const statistics = reactive<Statistics>({
  countTimes: 0,
  gainQuantity: 0,
  lossQuantity: 0,
  gainCostAmount: 0,
  lossCostAmount: 0
})

const tableData = ref<InventoryStatRow[]>([])
const loading = ref(false)

const page = reactive({
  pageindex: 1,
  pagesize: 10,
  listCount: 0
})

onMounted(() => {
  loadCountTypes()
  loadWarehouses()
  applyQuickRange('thisMonth')
  fetchData()
})

const loadCountTypes = async () => {
  try {
    const res = await myaxios.get('/api/InventoryCount/GetCountType')
    if (res.data?.code === 200 || res.data?.success) {
      countTypeOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取盘点类型失败:', error)
  }
}

const loadWarehouses = async () => {
  try {
    const res = await myaxios.get('/api/Warehousing/GetWarehouse')
    if (res.data?.code === 200 || res.data?.success) {
      warehouseOptions.value = (res.data.data || []).map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseName: item.warehouseName
      }))
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

const getQuickRange = (tab: QuickDateTab): [string, string] => {
  const today = moment()
  switch (tab) {
    case 'today':
      return [today.clone().startOf('day').format('YYYY-MM-DD'), today.clone().endOf('day').format('YYYY-MM-DD')]
    case 'yesterday': {
      const y = today.clone().subtract(1, 'day')
      return [y.startOf('day').format('YYYY-MM-DD'), y.endOf('day').format('YYYY-MM-DD')]
    }
    case 'thisWeek':
      return [today.clone().startOf('week').format('YYYY-MM-DD'), today.clone().endOf('week').format('YYYY-MM-DD')]
    case 'lastWeek': {
      const last = today.clone().subtract(1, 'week')
      return [last.startOf('week').format('YYYY-MM-DD'), last.endOf('week').format('YYYY-MM-DD')]
    }
    case 'thisMonth':
      return [today.clone().startOf('month').format('YYYY-MM-DD'), today.clone().endOf('month').format('YYYY-MM-DD')]
    case 'lastMonth': {
      const lastMonth = today.clone().subtract(1, 'month')
      return [lastMonth.startOf('month').format('YYYY-MM-DD'), lastMonth.endOf('month').format('YYYY-MM-DD')]
    }
    default:
      return ['', '']
  }
}

const applyQuickRange = (tab: QuickDateTab) => {
  if (tab === 'custom') {
    if (!queryForm.countDateRange || queryForm.countDateRange.length === 0) {
      queryForm.countDateRange = []
    }
    return
  }
  const [start, end] = getQuickRange(tab)
  queryForm.countDateRange = [start, end]
}

const handleDateTabChange = (value: QuickDateTab) => {
  activeDateTab.value = value
  applyQuickRange(value)
  if (value !== 'custom') {
    page.pageindex = 1
    fetchData()
  }
}

const handleCustomCountDateChange = () => {
  activeDateTab.value = 'custom'
}

const handleQuery = () => {
  page.pageindex = 1
  fetchData()
}

const handleReset = () => {
  queryForm.product = ''
  queryForm.productCode = ''
  queryForm.inventoryCountCode = ''
  queryForm.countTypeId = null
  queryForm.unit = ''
  queryForm.warehouseId = null
  queryForm.handler = ''
  queryForm.documentCreator = ''
  queryForm.organizationName = ''
  queryForm.countDateRange = []
  queryForm.documentCreationRange = []
  activeDateTab.value = 'thisMonth'
  applyQuickRange('thisMonth')
  page.pageindex = 1
  fetchData()
}

const fetchData = async () => {
  loading.value = true
  try {
    const params: any = {
      product: queryForm.product || undefined,
      productCode: queryForm.productCode || undefined,
      inventoryCountCode: queryForm.inventoryCountCode || undefined,
      countTypeId: queryForm.countTypeId || undefined,
      unit: queryForm.unit || undefined,
      warehouseId: queryForm.warehouseId || undefined,
      handler: queryForm.handler || undefined,
      documentCreator: queryForm.documentCreator || undefined,
      organizationName: queryForm.organizationName || undefined,
      countDateStart: queryForm.countDateRange?.[0] || undefined,
      countDateEnd: queryForm.countDateRange?.[1] || undefined,
      documentCreationStart: queryForm.documentCreationRange?.[0] || undefined,
      documentCreationEnd: queryForm.documentCreationRange?.[1] || undefined,
      pageindex: page.pageindex,
      pagesize: page.pagesize
    }

    Object.keys(params).forEach((key) => {
      if (params[key] === undefined || params[key] === null || params[key] === '') {
        delete params[key]
      }
    })

    const [listRes, statRes] = await Promise.all([
      myaxios.get('/api/InventoryCount/GetInventoryCountStatistics', { params }),
      myaxios.get('/api/InventoryCount/GetInventoryCountStatisticsSummary', {
        params: { ...params, pageindex: undefined, pagesize: undefined }
      })
    ])

    if (listRes.data?.code === 200 || listRes.data?.success) {
      const data = listRes.data.data || {}
      const rows: InventoryStatRow[] = (data.data || data.items || []).map((item: any) => ({
        productId: item.productId ?? 0,
        productCode: item.productCode || '',
        productName: item.productName || '',
        countResult: item.countResult ?? 0,
        countResultText: item.countResultText || '',
        specificationModel: item.specificationModel || '',
        unitName: item.unitName || '',
        productTypeName: item.productTypeName || '',
        bookedQuantity: item.bookedQuantity ?? 0,
        countQuantity: item.countQuantity ?? 0,
        gainQuantity: item.gainQuantity ?? 0,
        lossQuantity: item.lossQuantity ?? 0,
        bookedAmount: item.bookedAmount ?? 0,
        countAmount: item.countAmount ?? 0,
        gainAmount: item.gainAmount ?? 0,
        lossAmount: item.lossAmount ?? 0,
        handlerName: item.handlerName || '',
        costUnitPrice: item.costUnitPrice ?? 0,
        costAmount: item.costAmount ?? 0,
        documentCreator: item.documentCreator || '',
        organizationName: item.organizationName || '',
        documentCreation: item.documentCreation
      }))
      tableData.value = rows
      page.listCount = data.listCount || data.total || rows.length
    }

    if (statRes.data?.code === 200 || statRes.data?.success) {
      const s = statRes.data.data || {}
      statistics.countTimes = s.countTimes ?? 0
      statistics.gainQuantity = s.gainQuantity ?? 0
      statistics.lossQuantity = s.lossQuantity ?? 0
      statistics.gainCostAmount = s.gainCostAmount ?? 0
      statistics.lossCostAmount = s.lossCostAmount ?? 0
    }
  } catch (error) {
    console.error('获取盘点统计数据失败:', error)
    ElMessage.error('获取盘点统计数据失败')
  } finally {
    loading.value = false
  }
}

const handleRefresh = () => {
  fetchData()
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const handleSizeChange = (size: number) => {
  page.pagesize = size
  page.pageindex = 1
  fetchData()
}

const handleCurrentChange = (index: number) => {
  page.pageindex = index
  fetchData()
}

const formatDate = (date?: string | Date) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD')
}

const formatAmount = (amount: number) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}
</script>

<style scoped>
.inventory-stat-page {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.quick-tabs {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.filter-form {
  margin-top: 10px;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 18px 12px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 6px;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.danger {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.table-card .table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>


